package cn.edu.hzw.criminalintent.fragmnet

import android.content.Context
import android.os.Bundle
import android.text.format.DateUtils
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.edu.hzw.criminalintent.R
import cn.edu.hzw.criminalintent.bean.Crime
import cn.edu.hzw.criminalintent.databinding.FragmentCrimeListBinding
import cn.edu.hzw.criminalintent.databinding.ItemCrimePoliceBinding
import cn.edu.hzw.criminalintent.databinding.ItemEmptyViewBinding
import cn.edu.hzw.criminalintent.databinding.ListItemCrimeBinding
import cn.edu.hzw.criminalintent.model.CrimeListViewModel
import cn.edu.hzw.criminalintent.utils.DateUtil
import java.util.*
import javax.security.auth.callback.Callback

private const val TAG = "CrimeListFragment"
class CrimeListFragment : Fragment() {
    private lateinit var mBinding : FragmentCrimeListBinding
    private var adapter:CrimeAdapter? = CrimeAdapter(emptyList())
    private var callbacks:Callbacks? = null
    private val crimeListViewModel:CrimeListViewModel by lazy {
        ViewModelProvider(this).get(CrimeListViewModel::class.java)
    }

    companion object{
        fun newInstance():CrimeListFragment{
            return CrimeListFragment()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /**
         * 设置菜单
         */
        setHasOptionsMenu(true)
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = FragmentCrimeListBinding.inflate(layoutInflater,container,false)
        mBinding.crimeRecyclerView.layoutManager = LinearLayoutManager(context)
        mBinding.crimeRecyclerView.adapter = adapter
        adapter?.showEmptyView()
        return mBinding.root
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        callbacks = context as Callbacks?
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val appCompatActivity = activity as AppCompatActivity
        val appBar = appCompatActivity.supportActionBar
        appBar?.title = appCompatActivity.resources.getString(R.string.some_cool_title)
        crimeListViewModel.crimeListLiveData.observe(
            viewLifecycleOwner,
            Observer { crimes ->
                crimes?.let {
                    Log.i(TAG, "Got crimes ${crimes.size}")
                    updateUI(crimes)
                }
            }
        )
    }

    /**
     * 菜单调用
     */
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.fragment_crime_list,menu)
    }

    /**
     * 菜单点击，响应菜单项选择事件
     */
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when(item.itemId){
            R.id.new_crime->{
                val crime = Crime()
                crimeListViewModel.addCrime(crime)
                callbacks?.onCrimeSelected(crime.id)
                true
            }
            else -> return super.onOptionsItemSelected(item)
        }
    }
    override fun onDetach() {
        super.onDetach()
        callbacks = null
    }

    private fun updateUI(crimes: List<Crime>) {
        adapter = CrimeAdapter(crimes)
        mBinding.crimeRecyclerView.adapter = adapter
    }

    private inner class CrimeHolder(val itemBinding:ListItemCrimeBinding): RecyclerView.ViewHolder(itemBinding.root) {
        private lateinit var crime: Crime

        /**
         * 检测用户点击事件
         */
        init {
            itemBinding.root.setOnClickListener {
//                Toast.makeText(context,"${crime.title}pressed!",Toast.LENGTH_SHORT).show()
                callbacks?.onCrimeSelected(crime.id)
            }
        }
        /**
         * 绑定参数
         */
        fun bind(crime: Crime){
            this.crime =crime
            itemBinding.crimeTitle.text = this.crime.title
            itemBinding.crimeDate.text = DateUtil.getDayAndWeek(crime.date)
            itemBinding.imageView.visibility = if (crime.isSolved){
                View.VISIBLE
            }else{
                View.GONE
            }
        }
    }

    private inner class CrimePoliceHolder(val itemPoliceBinding:ItemCrimePoliceBinding):
            RecyclerView.ViewHolder(itemPoliceBinding.root){
        private lateinit var crimes:Crime
        init {
            itemPoliceBinding.root.setOnClickListener {
                callbacks?.onCrimeSelected(crimes.id)
            }
        }
        fun bind(crime: Crime){
            this.crimes = crime
            itemPoliceBinding.itemCrimeTitle.text = crime.title
            itemPoliceBinding.itemCrimeDate.text = DateUtil.getDayAndWeek(crime.date)
        }
    }

    private inner class EmptyHolder(val itemEmptyViewBinding: ItemEmptyViewBinding):
    RecyclerView.ViewHolder(itemEmptyViewBinding.root){
        init {
            itemEmptyViewBinding.imgAddCrime.setOnClickListener {
                val crime = Crime()
                crimeListViewModel.addCrime(crime)
                callbacks?.onCrimeSelected(crime.id)
            }
        }
    }

    private inner class CrimeAdapter(var crimes:List<Crime>):RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        /**
         * 是否显示空布局，默认不显示
         */
        private var showEmptyView = false
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return when(viewType) {
                ITEM_TYPE.ITEM_TYPE_POLICE.ordinal ->
                    CrimePoliceHolder(
                        ItemCrimePoliceBinding.inflate(
                            LayoutInflater.from(parent.context),
                            parent,
                            false
                        )
                    )
                ITEM_TYPE.ITEM_TYPE_NOMAL.ordinal ->
                    CrimeHolder(
                        ListItemCrimeBinding.inflate(
                            LayoutInflater.from(parent.context),
                            parent,
                            false
                        )
                    )
                else ->
                    EmptyHolder(
                        ItemEmptyViewBinding.inflate(
                            LayoutInflater.from(parent.context),
                            parent,
                            false
                        )
                    )
            }

        }

        override fun getItemViewType(position: Int): Int {
            return if (position == 0&&isEmptyPosition()){
                ITEM_TYPE.ITEM_TYPE_EMPTY.ordinal
            }else{
                if (crimes[position].requiresPolice){
                    ITEM_TYPE.ITEM_TYPE_POLICE.ordinal
                }else{
                    ITEM_TYPE.ITEM_TYPE_NOMAL.ordinal
                }
            }
        }
        override fun getItemCount(): Int {
           val count = crimes.size
            return if (count>0){
                showEmptyView = false
                count
            }else{
                if (showEmptyView){
                    1
                }else{
                    0
                }
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (!(position == 0&&isEmptyPosition())){
                val crime = crimes[position]
                if (holder is CrimeHolder){
                    holder.bind(crime)
                }else if (holder is CrimePoliceHolder){
                    holder.bind(crime)
                }
            }
        }
        /**
         * Show empty view
         * 显示空布局
         */
        fun showEmptyView(){
            showEmptyView = true
            notifyDataSetChanged()
        }

        /**
         * 判断是否是空布局
         */
        fun isEmptyPosition():Boolean{
            val count = if (crimes.isEmpty()) 0 else crimes.size
            return showEmptyView && count == 0
        }

    }

    enum class ITEM_TYPE{
        ITEM_TYPE_NOMAL,
        ITEM_TYPE_POLICE,
        ITEM_TYPE_EMPTY
    }
    interface Callbacks{
        fun onCrimeSelected(crimeId:UUID)
    }
}